package com.ruoyi.mes.utils;

import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MqttConfig {
    private static final String BROKER_URL = "tcp://120.55.114.101:1883";
    private static final String USERNAME = "chanxian1";
    private static final String PASSWORD = "aaaa1234";
    private static final String CLIENT_ID = "chanxian12";

    @Bean
    public MqttClient mqttClient() throws MqttException {
        MqttClient client = new MqttClient(BROKER_URL, CLIENT_ID, new MemoryPersistence());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(USERNAME);
        options.setPassword(PASSWORD.toCharArray());
        options.setAutomaticReconnect(true);
        options.setCleanSession(true);
        options.setConnectionTimeout(10);

        try {
            client.connect(options);
            if (client.isConnected()) {
                System.out.println("已成功连接到MQTT服务器");
            }

        } catch (MqttException e) {
            throw new RuntimeException("MQTT连接失败: " + e.getMessage(), e);
        }

        return client;
    }
}
